//
//  AddTagViewController.m
//  SoundPill
//
//  Created by 宋旭东®Des on 15/2/3.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "AddTagViewController.h"
#import "ZFTokenField.h"
#import "TokenView.h"
#import "AFNetworking.h"
#import "HotTagCollectionViewCell.h"
#import "NSString+URL.h"


@interface AddTagViewController ()<ZFTokenFieldDataSource,
    ZFTokenFieldDelegate,
    UITextFieldDelegate,
    UICollectionViewDataSource,
    UICollectionViewDelegateFlowLayout>
{
    UIFont *font;
    float fieldWidth;
    float fieldX;
    NSMutableArray *textarray;
    NSString *filePath;
}
@property (strong, nonatomic) ZFTokenField *tokenField;
@property (strong, nonatomic) NSMutableArray *tokens;
@property (strong, nonatomic) NSMutableArray *tokenHistroy;
@property (strong, nonatomic) UIAlertView *textAlert;
@property (strong, nonatomic) UIAlertView *tagAlert;
@property (strong, nonatomic) UITextField *tempField;
@property (strong, nonatomic) UIButton *rightButton;
//热门标签
@property (strong, nonatomic) UICollectionView *HotTagView;
@end

@implementation AddTagViewController
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.tokens = [NSMutableArray array];
        textarray = [NSMutableArray array];
        NSFileManager *manager = [NSFileManager defaultManager];
        NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        // 传递 0 代表是找在Documents 目录下的文件。
        NSString *documentDirectory = [directoryPaths objectAtIndex:0];
        filePath = [documentDirectory stringByAppendingPathComponent:@"tagHistory"];
        if (![manager fileExistsAtPath:filePath]) {
            [manager createFileAtPath:filePath contents:nil attributes:nil];
            self.tokenHistroy = [[NSMutableArray alloc] init];
        } else {
            self.tokenHistroy = [NSMutableArray arrayWithContentsOfFile:filePath];
            [textarray addObjectsFromArray:_tokenHistroy];
        }
    }
    return self;
}

#pragma mark -
#pragma mark 请求热门标签
- (void)getHotTags{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *dic = [defaults objectForKey:@"authorization"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [manager GET:@"http://123.57.1.143/api/tag/recommand" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *jsonData = [operation.responseString dataUsingEncoding:NSUTF8StringEncoding];
        NSError *error;
        NSDictionary *hotTagDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
        NSArray *array = [hotTagDic objectForKey:@"data"];
        for (NSDictionary *temp in array) {
            [textarray addObject:[temp objectForKey:@"name"]];
        }
        [_HotTagView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"%@", error);
    }];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];
    self.title = @"标签";
    [self createNavigationView];
    [self createZFToken];
    [self createHotTag];
    [self createAlert];
    // Do any additional setup after loading the view.
}

- (void)createNavigationView
{
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.tag = 36;
    [leftButton setImage:[UIImage imageNamed:@"backButton"] forState:UIControlStateNormal];
    leftButton.frame = CGRectMake(0, 0, 30, 30);
    [leftButton addTarget:self action:@selector(touchNavigationButton:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftItem;

    self.rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _rightButton.tag = 45;
    [_rightButton setImage:[UIImage imageNamed:@"done"] forState:UIControlStateNormal];
    _rightButton.frame = CGRectMake(0, 0, 30, 30);
    [_rightButton addTarget:self action:@selector(touchNavigationButton:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:_rightButton];
    self.navigationItem.rightBarButtonItem = backItem;
    if (_tokens.count == 0) {
        _rightButton.hidden = YES;
    }
}

#pragma mark -
#pragma mark 导航栏按钮方法
- (void)touchNavigationButton:(UIButton *)sender
{
    if (sender.tag == 36) {
        [self.tokenField.textField resignFirstResponder];
        [self.navigationController popViewControllerAnimated:YES];
        
    } else if (sender.tag == 45) {
        if (_tokens.count > 0) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"tagArray" object:_tokens];
            [self.tokenField.textField resignFirstResponder];
            [_tokenHistroy writeToFile:filePath atomically:YES];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

#pragma mark -
#pragma mark 创建ZFToken
- (void)createZFToken
{
    self.tokenField = [[ZFTokenField alloc] initWithFrame:CGRectMake(5, 7, self.view.frame.size.width - 10, self.view.frame.size.height / 3 - 30)];
    _tokenField.backgroundColor = [UIColor whiteColor];
    _tokenField.userInteractionEnabled = YES;
    _tokenField.delegate = self;
    _tokenField.dataSource = self;
    [self.tokenField.textField becomeFirstResponder];
    [_tokenField.textField setReturnKeyType:UIReturnKeyDone];
    [self.view addSubview:_tokenField];
    UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(5, _tokenField.frame.origin.y + _tokenField.frame.size.height + 5 , self.view.frame.size.width - 10, 5)];
    line.image = [UIImage imageNamed:@"gray"];
    [self.view addSubview:line];
}

#pragma mark -
#pragma mark ZFToken DataSource
- (CGFloat)lineHeightForTokenInField:(ZFTokenField *)tokenField
{
    return 25;
}

- (NSUInteger)numberOfTokenInField:(ZFTokenField *)tokenField
{
    return _tokens.count;
}

- (UIView *)tokenField:(ZFTokenField *)tokenField viewForTokenAtIndex:(NSUInteger)index
{
    TokenView *tokenView = [[TokenView alloc] init];
    tokenView.userInteractionEnabled = YES;
    tokenView.backgroundColor = [UIColor whiteColor];
//    tokenView.layer.cornerRadius = 10;
    tokenView.layer.borderColor = [UIColor blackColor].CGColor;
    tokenView.layer.borderWidth = 2;
    tokenView.tokenLabel.frame = CGRectMake(10, 0, self.view.frame.size.width, 25);
    tokenView.tokenLabel.textColor = [UIColor blackColor];
    tokenView.tokenLabel.text = self.tokens[index];
    CGSize size = [tokenView.tokenLabel sizeThatFits:CGSizeMake(1000, 25)];
    tokenView.frame = CGRectMake(0, 0, size.width + 20, 25);
    UIButton *deleteTag = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteTag.backgroundColor = [UIColor clearColor];
    deleteTag.alpha = 0.3;
    deleteTag.layer.cornerRadius = 10;
    deleteTag.tag = index;
    deleteTag.frame = CGRectMake(0, 0, tokenView.bounds.size.width, tokenView.bounds.size.height);
    [deleteTag addTarget:self action:@selector(deleteTag:) forControlEvents:UIControlEventTouchUpInside];
    [tokenView addSubview:deleteTag];
    return tokenView;
}
#pragma mark - ZFTokenField Delegate
- (CGFloat)tokenMarginInTokenInField:(ZFTokenField *)tokenField
{
    return 2;
}

- (void)tokenField:(ZFTokenField *)tokenField didReturnWithText:(NSString *)text
{
    if (![text isEqualToString:@""]) {
        if (text.length <= 20) {
            if (_tokens.count < 5) {
                [self.tokens addObject:text];
                [tokenField reloadData];
                [self.tokenField.textField becomeFirstResponder];
                if (_tokenHistroy.count > 0) {
                    if (![_tokenHistroy containsObject:text]) {
                        if (_tokenHistroy.count < 7) {
                            [_tokenHistroy addObject:text];
                        } else {
                            [_tokenHistroy removeObjectAtIndex:0];
                            [_tokenHistroy addObject:text];
                        }
                    }
                } else {
                    [_tokenHistroy addObject:text];
                }
            } else {
                [self.tagAlert show];
                tokenField.textField.text = @"";
                [tokenField reloadData];
            }
        }
        _rightButton.hidden = NO;
    }
}

- (void)tokenField:(ZFTokenField *)tokenField didRemoveTokenAtIndex:(NSUInteger)index
{
    [self.tokens removeObjectAtIndex:index];
    [_tokenField reloadData];
}

- (BOOL)tokenFieldShouldEndEditing:(ZFTokenField *)textField
{
    return YES;
}

- (void)tokenField:(ZFTokenField *)tokenField didTextChanged:(NSString *)text{
    [self textLength:text];
}

- (void)deleteTag:(UIButton *)sender{
        TokenView *token = (TokenView *)sender.nextResponder;
    if (token.state==0) {
        token.frame = CGRectMake(token.frame.origin.x, token.frame.origin.y, token.frame.size.width +20, token.frame.size.height);
    UIButton *del = [UIButton buttonWithType:UIButtonTypeCustom];
    del.frame = CGRectMake(token.frame.size.width - 23, 0, 20, token.frame.size.height - 3);
    del.backgroundColor = [UIColor clearColor];
    del.tag = sender.tag;
    [del setTitle:@"x" forState:UIControlStateNormal];
    [del setTitleColor:[UIColor colorWithWhite:1.000 alpha:0.490] forState:UIControlStateNormal];
    [del addTarget:self action:@selector(removeTagFromToken:) forControlEvents:UIControlEventTouchUpInside];
    [token addSubview:del];
        token.state = 1;
    }
}
- (void)removeTagFromToken:(UIButton *)sender
{
    [_tokens removeObjectAtIndex:sender.tag];
    [_tokenField reloadData];
}
- (void)textLength:(NSString *)text{
    if (text.length > 20) {
        [_textAlert show];
        _tokenField.textField.text = @"";
    }
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.tokenField.textField resignFirstResponder];
}
#pragma mark - 
#pragma mark 热门标签列表
- (void)createHotTag
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
//    layout.itemSize = CGSizeMake(100, 100);
    [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
//    [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
//    layout.estimatedItemSize = CGSizeMake(300, 30);
    layout.minimumLineSpacing = 5;
    layout.minimumInteritemSpacing = 5 ;
    layout.sectionInset = UIEdgeInsetsMake(5, 5, 0, 5);
    self.HotTagView = [[UICollectionView alloc] initWithFrame:CGRectMake(5, _tokenField.frame.origin.y + _tokenField.frame.size.height + 15, self.view.frame.size.width - 10, self.view.frame.size.height / 3 - 50) collectionViewLayout:layout];
    _HotTagView.delegate = self;
    _HotTagView.dataSource = self;
    _HotTagView.scrollEnabled = NO;
    _HotTagView.backgroundColor = [UIColor clearColor];
    //注册 cell
    [_HotTagView registerClass:[HotTagCollectionViewCell class] forCellWithReuseIdentifier:@"HotTagItem"];
    [self.view addSubview:_HotTagView];
    [self getHotTags];
}

#pragma mark -
#pragma mark collectionView 协议
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [textarray count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HotTagCollectionViewCell *hotTagItem = [collectionView dequeueReusableCellWithReuseIdentifier:@"HotTagItem" forIndexPath:indexPath];
    hotTagItem.backgroundColor = [UIColor whiteColor];
    hotTagItem.hotTagText.text = textarray[indexPath.row];
    hotTagItem.hotTagText.textColor = [UIColor blackColor];
    hotTagItem.layer.borderWidth = 2;
    hotTagItem.layer.borderColor = [UIColor blackColor].CGColor;
//    hotTagItem.layer.cornerRadius = 10;
    return hotTagItem;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *str = textarray[indexPath.row];
    CGSize titlesize = [str sizeWithAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Arial" size:16]}];
    CGSize newSize = CGSizeMake(titlesize.width + 10, titlesize.height + 10);
    return newSize;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_tokens.count < 5) {
        [self.tokens addObject:[textarray objectAtIndex:indexPath.row]];
        _rightButton.hidden = NO;
    } else {
        [_tagAlert show];
    }
    [self.tokenField reloadData];
}

#pragma mark -
#pragma mark alertView
- (void)createAlert
{
    self.textAlert = [[UIAlertView alloc] initWithTitle:nil message:@"每个标签最多输入20字" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    self.tagAlert = [[UIAlertView alloc] initWithTitle:nil message:@"最多5个标签" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
